package helper

import (
	"errors"
	"fmt"
	"io"
	"net/http"
	"strings"
)

// const ua string = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36"
const ua string = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"

// HttpGet httpget
func HttpGet(url string) []byte {
	ul := url
	// 创建 http 客户端
	client := &http.Client{}
lab1:
	// 创建请求
	req, _ := http.NewRequest("GET", ul, nil)
	req.Header.Set("User-Agent", ua)
	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		// 返回错误
		fmt.Println("\r请求出错 ", err)
		ul = strings.Replace(url, "https", "http", -1)
		if ul != url {
			fmt.Println("\r 重新请求http")
			goto lab1
		}
	}
	// 最后关闭连接
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			return
		}
	}(resp.Body)
	// 读取内容
	//fmt.Print("\tStatusCode", resp.StatusCode)
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(errors.New(fmt.Sprintf("解析内容出错 %s", err)))
		return []byte("")
	}
	return body
}
